<template>
  <div class="table-box">
    <div class="header">
      <button class="nav-button" @click="goToPreviousStep">上一步</button>
      <div class="steps-container">
        <div v-for="(step, index) in steps" :key="index" :class="['step-box', { active: index === 2 }]">
          {{ step }}
        </div>
      </div>
      <button class="nav-button" @click="handleNext">下一步</button>
    </div>
    <ProTable ref="proTable" title="生产活动列表" :columns="columns" :data="projectActivities">
      <!-- 表格 header 按钮 -->
      <!-- <template #tableHeader>
        <div class="header-container">
          <SelectFilter :data="filterData" @change="changeFilter" :default-values="filterResult" />
        </div>
      </template> -->
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="goToModal(scope.row)">碳排放数值收集</el-button>
      </template>
    </ProTable>
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onMounted } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { EditPen } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();

const router = useRouter();
const route = useRoute();

// 从路由参数中获取 projectId
const projectId = route.params.projectId;

// const filterResult = ref({ state: "1" });
// const changeFilter = (val: typeof filterResult.value) => {
//   filterResult.value = val;
//   if (val.state === "2") {
//     router.push({
//       path: `/lca/inventory/productIndex/${projectId}`
//     });
//   }
// };

const steps = ["产品碳排放源分析", "外购零部件碳排放值收集", "产品生产装配碳排放值收集"];

// 上一步
const goToPreviousStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/inventory/structureTree/${projectId}`);
};

// 获取流程图数据
const fetchFlowChartList = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getAllFlowcharts`, {
      params: { projectId }
    });
    console.log("res.data.data!!!", res.data.data);
    if (res.data?.code === 200) {
      return res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || "获取流程图失败");
      return [];
    }
  } catch (error) {
    console.error("获取流程图出错:", error);
    ElMessage.error("获取流程图失败");
    return [];
  }
};

// 修改下一步按钮的处理函数
const handleNext = async () => {
  // 从后端获取流程图数据
  const flowChartData = await fetchFlowChartList();
  const hasAllocationDataSource = flowChartData.some((flowChart: any) =>
    flowChart.nodes?.some((node: any) => node.inputNodes?.some((input: any) => input.dataSource === "分配获取"))
  );
  console.log("hasAllocationDataSource!!!", hasAllocationDataSource);
  const storageKey = `needAllocation_${projectId}`;
  if (hasAllocationDataSource) {
    localStorage.setItem(storageKey, "true");
  } else {
    // 如果没有分配节点，删除对应的 localStorage
    localStorage.removeItem(storageKey);
  }

  const carbonEmissionStorageKey = `processCarbonEmission_${projectId}`;
  localStorage.setItem(carbonEmissionStorageKey, JSON.stringify(flowChartData));
  console.log("将流程图节点数据存入 localStorage:", carbonEmissionStorageKey);

  if (hasAllocationDataSource) {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push(`/lca/impact/allocation/${projectId}`);
  } else {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push(`/lca/impact/index/${projectId}`);
  }
};

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const goToModal = (row: any) => {
  // 如果是产品装配（materialId为0），使用特殊的路由参数
  if (row.materialId === "0") {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push({
      path: `/lca/inventory/processFlow/${projectId}/0/0`
    });
  } else {
    // 其他情况保持原有逻辑
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push({
      path: `/lca/inventory/processFlow/${projectId}/1/${row.materialId}`
    });
  }
};

interface MaterialEmission {
  projectId: string;
  materialId: string;
  materialName: string;
  emissions: string;
}

const projectActivities = ref<MaterialEmission[]>([]);
const selfEmissionList = ref<any[]>([]);
const assemblyEmission = ref<any>(null);
const baseUrl = import.meta.env.VITE_BASE_URL;

// 获取自制物料碳排放源列表
const getSelfEmissionList = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getSelfMadeMaterial`, {
      params: { projectId }
    });
    if (res.data?.code === 200) {
      selfEmissionList.value = res.data.data || [];
      buildTableData();
    } else {
      ElMessage.warning(res.data?.msg || "获取自制物料失败");
    }
  } catch (error) {
    console.error("获取自制物料失败:", error);
    ElMessage.warning("获取自制物料失败");
  }
};

// 获取装配碳排放源
const getAssemblyEmission = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/initAssemblyEmission`, {
      params: { projectId }
    });
    if (res.data?.code === 200) {
      assemblyEmission.value = res.data.data;
      buildTableData();
    } else {
      ElMessage.warning(res.data?.msg || "获取产品装配碳排放源失败");
    }
  } catch (error) {
    console.error("获取产品装配碳排放源失败:", error);
    ElMessage.warning("获取产品装配碳排放源失败");
  }
};

// 构建表格数据
const buildTableData = () => {
  const base = selfEmissionList.value.map(item => ({
    projectId: projectId as string,
    materialId: item.materialId,
    materialName: item.materialName + "制造",
    emissions: item.emissions || "暂未定义"
  }));

  if (assemblyEmission.value) {
    base.push({
      projectId: projectId as string,
      materialId: "0",
      materialName: "产品装配",
      emissions: assemblyEmission.value.emissions || "暂未定义"
    });
  }

  projectActivities.value = base;
};

onMounted(async () => {
  // 获取自制物料和装配碳排放源数据
  await Promise.all([getSelfEmissionList(), getAssemblyEmission()]);
});

// 修改表格配置项以匹配新的数据结构
const columns: ColumnProps<MaterialEmission>[] = [
  {
    prop: "materialName",
    label: "生产活动"
  },
  {
    prop: "emissions",
    label: "碳排放源"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 400 }
];
</script>

<style>
/* 确保 ElMessage 显示在最上层 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  margin-bottom: 20px; /* 添加底部间距 */
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.nav-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
.nav-button:hover {
  background-color: #007d6a;
}
.steps-container {
  display: flex;
  justify-content: space-between;
  width: 80%;
  padding: 0 20px;
}
.step-box {
  position: relative;
  flex: 1;
  padding: 15px 10px;
  margin: 0 10px;
  color: #777777;
  text-align: center;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s;
}
.step-box.active {
  font-weight: bold;
  color: #009688;
  background-color: #e6f5f3;
  border-color: #009688;
}
.step-box::after {
  position: absolute;
  top: 50%;
  right: -20px;
  font-size: 20px;
  color: #009688;
  content: "→";
  transform: translateY(-50%);
}
.step-box:last-child::after {
  visibility: hidden;
}

/* 添加新的样式 */
.header-container {
  display: flex;
  align-items: center;
}

/* 数据来源选择对话框样式 */
.data-source-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}
.data-source-option {
  display: flex;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e6f5f3;
  border-radius: 8px;
  transition: all 0.3s;
}
.data-source-option:hover {
  border-color: #009688;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}
.source-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 16px;
  color: #009688;
  background: #e6f5f3;
  border-radius: 8px;
}
.source-info {
  flex: 1;
}
.source-info h4 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #303133;
}
.source-info p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
</style>
